#!/bin/bash

function append_contents
{
	FILE="$1"
	ORIG="$1.orig"

	cat "$ORIG" >> "$FILE"
	check_status_fatal $? "Failed to append original contents."
}

function backup_orig
{
	FILE="$1"
	ORIG="${FILE}.orig"

	mv "$FILE" "$ORIG"
	check_status_fatal $? "Failed to move \'$FILE\' to \'$ORIG\'"
}

function begin_with_copyright
{
	FILE="$1"

	echo "/*" 1>"$FILE" && \
		echo " * Intern's Quest is an adventure game." 1>>"$FILE" && \
		echo " * Copyright (C) 2009 Brandon McCaig, Samuel Henderson" 1>>"$FILE" && \
		echo " *" 1>>"$FILE" && \
		echo " * This file is part of Intern's Quest." 1>>"$FILE" && \
		echo " *" 1>>"$FILE" && \
		echo " * Intern's Quest is free software: you can redistribute it and/or modify" 1>>"$FILE" && \
		echo " * it under the terms of the GNU General Public License as published by" 1>>"$FILE" && \
		echo " * the Free Software Foundation, either version 2 of the License, or" 1>>"$FILE" && \
		echo " * (at your option) any later version." 1>>"$FILE" && \
		echo " *" 1>>"$FILE" && \
		echo " * Intern's Quest is distributed in the hope that it will be useful," 1>>"$FILE" && \
		echo " * but WITHOUT ANY WARRANTY; without even the implied warranty of" 1>>"$FILE" && \
		echo " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the" 1>>"$FILE" && \
		echo " * GNU General Public License for more details." 1>>"$FILE" && \
		echo " *" 1>>"$FILE" && \
		echo " * You should have received a copy of the GNU General Public License" 1>>"$FILE" && \
		echo " * along with Intern's Quest.  If not, see <http://www.gnu.org/licenses/>." 1>>"$FILE" && \
		echo " */" 1>>"$FILE" && \
		echo 1>>"$FILE"

	check_status_fatal $? "Failed to initialize \'$FILE\' with copyright."
}

function check_args
{
	COMMAND="$1"
	FILE="$2"

	if [ "$FILE" == "" ]; then
		echo "Usage: $COMMAND FILE" 1>&2
		exit 1
	fi
}

function check_status
{
	STATUS="$1"
	ERRMSG="$2"

	if [ "$STATUS" != '0' ]; then
		echo "$ERRMSG" 1>&2
	fi
}

function check_status_fatal
{
	STATUS="$1"
	ERRMSG="$2"

	if [ "$STATUS" != '0' ]; then
		echo "$ERRMSG" 1>&2
		exit 1
	fi
}

function main
{
	COMMAND="$1"
	FILE="$2"

	check_args "$@"
	backup_orig "$FILE"
	begin_with_copyright "$FILE"
	append_contents "$FILE"
	remove_backup "$FILE"
}

function remove_backup
{
	BACKUP="$1.orig"

	rm "$BACKUP"

	check_status $? "Failed to remove backup \'$BACKUP\'"
}

main "$0" "$@"
